#!/bin/bash

# DevOps系统部署前检查脚本
# 检查系统环境、依赖和配置

set -e

echo "🚀 DevOps系统部署前检查"
echo "=========================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查函数
check_command() {
    if command -v $1 &> /dev/null; then
        echo -e "${GREEN}✅ $1 已安装${NC}"
        return 0
    else
        echo -e "${RED}❌ $1 未安装${NC}"
        return 1
    fi
}

check_python_version() {
    echo "🐍 检查Python版本..."
    if python3 --version | grep -E "Python 3\.(9|10|11|12)" > /dev/null; then
        echo -e "${GREEN}✅ Python版本符合要求${NC}"
        python3 --version
        return 0
    else
        echo -e "${RED}❌ Python版本不符合要求 (需要 >= 3.9)${NC}"
        python3 --version
        return 1
    fi
}

check_node_version() {
    echo "📦 检查Node.js版本..."
    if node --version | grep -E "v(18|19|20|21)" > /dev/null; then
        echo -e "${GREEN}✅ Node.js版本符合要求${NC}"
        node --version
        return 0
    else
        echo -e "${RED}❌ Node.js版本不符合要求 (需要 >= 18.0)${NC}"
        node --version 2>/dev/null || echo "Node.js未安装"
        return 1
    fi
}

check_system_packages() {
    echo "📋 检查系统包..."
    local packages=("git" "curl" "wget" "unzip")
    local missing=0
    
    for pkg in "${packages[@]}"; do
        if ! check_command $pkg; then
            missing=$((missing + 1))
        fi
    done
    
    return $missing
}

check_project_structure() {
    echo "📁 检查项目结构..."
    local required_files=(
        "devops-backend/requirements.txt"
        "devops-backend/manage.py"
        "devops-backend/devops/settings.py"
        "devops-frontend/package.json"
        "devops-frontend/src/main.ts"
        "README.md"
    )
    
    local missing=0
    for file in "${required_files[@]}"; do
        if [[ -f "$file" ]]; then
            echo -e "${GREEN}✅ $file${NC}"
        else
            echo -e "${RED}❌ $file 不存在${NC}"
            missing=$((missing + 1))
        fi
    done
    
    return $missing
}

check_hardcoded_paths() {
    echo "🔍 检查硬编码路径..."
    local files_to_check=(
        "devops-backend/devops/settings.py"
        "devops-backend/regenerate_routes.py"
        "devops-backend/apps/unified_menu/services.py"
    )
    
    local found=0
    for file in "${files_to_check[@]}"; do
        if [[ -f "$file" ]]; then
            if grep -q "/code/devops" "$file"; then
                echo -e "${RED}❌ $file 包含硬编码路径 /code/devops${NC}"
                found=$((found + 1))
            else
                echo -e "${GREEN}✅ $file 无硬编码路径${NC}"
            fi
        fi
    done
    
    return $found
}

create_directories() {
    echo "📂 创建必要目录..."
    local dirs=(
        "devops-backend/logs"
        "devops-backend/media"
        "devops-backend/media/avatars"
        "devops-backend/static"
    )
    
    for dir in "${dirs[@]}"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            echo -e "${GREEN}✅ 创建目录: $dir${NC}"
        else
            echo -e "${GREEN}✅ 目录已存在: $dir${NC}"
        fi
    done
}

check_backend_dependencies() {
    echo "🔧 检查后端依赖..."
    if [[ -f "devops-backend/requirements.txt" ]]; then
        cd devops-backend
        if python3 -m pip check > /dev/null 2>&1; then
            echo -e "${GREEN}✅ 后端依赖检查通过${NC}"
            cd ..
            return 0
        else
            echo -e "${YELLOW}⚠️  后端依赖可能有问题，建议运行: pip install -r requirements.txt${NC}"
            cd ..
            return 1
        fi
    else
        echo -e "${RED}❌ requirements.txt 不存在${NC}"
        return 1
    fi
}

check_frontend_dependencies() {
    echo "🎨 检查前端依赖..."
    if [[ -f "devops-frontend/package.json" ]]; then
        if [[ -d "devops-frontend/node_modules" ]]; then
            echo -e "${GREEN}✅ 前端依赖已安装${NC}"
            return 0
        else
            echo -e "${YELLOW}⚠️  前端依赖未安装，建议运行: cd devops-frontend && npm install${NC}"
            return 1
        fi
    else
        echo -e "${RED}❌ package.json 不存在${NC}"
        return 1
    fi
}

# 主检查流程
main() {
    local total_checks=0
    local passed_checks=0
    
    # 系统环境检查
    echo -e "\n${YELLOW}=== 系统环境检查 ===${NC}"
    
    if check_python_version; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    if check_node_version; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    if check_system_packages; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    # 项目结构检查
    echo -e "\n${YELLOW}=== 项目结构检查 ===${NC}"
    
    if check_project_structure; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    if check_hardcoded_paths; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    # 创建必要目录
    echo -e "\n${YELLOW}=== 环境准备 ===${NC}"
    create_directories
    
    # 依赖检查
    echo -e "\n${YELLOW}=== 依赖检查 ===${NC}"
    
    if check_backend_dependencies; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    if check_frontend_dependencies; then passed_checks=$((passed_checks + 1)); fi
    total_checks=$((total_checks + 1))
    
    # 总结
    echo -e "\n${YELLOW}=========================="
    echo "📊 检查结果总结"
    echo -e "==========================${NC}"
    echo "通过: $passed_checks/$total_checks"
    
    if [[ $passed_checks -eq $total_checks ]]; then
        echo -e "${GREEN}🎉 所有检查通过！系统可以部署${NC}"
        echo -e "\n${GREEN}下一步：${NC}"
        echo "1. cd devops-backend && python manage.py migrate"
        echo "2. cd devops-backend && python manage.py createsuperuser"
        echo "3. 按照README.md进行部署"
        return 0
    else
        echo -e "${RED}⚠️  存在问题，请修复后重新检查${NC}"
        echo -e "\n${YELLOW}建议：${NC}"
        echo "1. 安装缺失的系统包"
        echo "2. 安装Python和Node.js依赖"
        echo "3. 修复硬编码路径问题"
        return 1
    fi
}

# 运行检查
main
exit $?
